package org.lg.framework.protocol.http;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.lg.framework.Invocation;
import org.lg.framework.register.LocalRegister;
import org.springframework.context.ApplicationContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class HttpHandler {
    //通用句柄调用方法
    public void handler(HttpServletRequest request, HttpServletResponse response, ApplicationContext context)  {
        ObjectMapper objectMapper = new ObjectMapper();

            //反序列化 json数据 得到调用对象需要的反射信息
        try {
            Invocation invocation = objectMapper.readValue(request.getInputStream(), Invocation.class);
            System.out.println(invocation);
            Class clazz = LocalRegister.get(invocation.getInterFaceName());//从本地注册中心得到 接口类
            Method method = clazz.getDeclaredMethod(invocation.getMethodName(), invocation.getParamTypes());
            //Object obj = clazz.newInstance();//如果是类 很明显可以直接调用 但是肯定是接口所有需要工厂模式,自定义接口或利用spring 容器技术
            Object obj = context.getBean(clazz.getSimpleName());//注意spring注册名字 和注册中心注册名字
            Object result = method.invoke(obj, invocation.getParamValues());

            IOUtils.write(objectMapper.writeValueAsString(result), response);
        } catch (NoSuchMethodException  | IllegalAccessException | InvocationTargetException | IOException e) {
            e.printStackTrace();
            IOUtils.write("非法操作", response);
        }

    }
}


